<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>贪吃蛇游戏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
            touch-action: none;
        }
        
        .game-container {
            position: relative;
            margin-bottom: 20px;
        }
        
        #gameCanvas {
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
            display: block;
        }
        
        .score-board {
            background: rgba(255, 255, 255, 0.9);
            padding: 15px 25px;
            border-radius: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }
        
        .score {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            text-align: center;
        }
        
        .controls {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 10px;
            margin-top: 20px;
            width: 200px;
            height: 200px;
        }
        
        .control-btn {
            background: rgba(255, 255, 255, 0.9);
            border: 2px solid #fff;
            border-radius: 10px;
            font-size: 24px;
            color: #667eea;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            user-select: none;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            transition: all 0.2s;
        }
        
        .control-btn:active {
            background: #667eea;
            color: white;
            transform: scale(0.95);
        }
        
        .up { grid-column: 2; grid-row: 1; }
        .left { grid-column: 1; grid-row: 2; }
        .right { grid-column: 3; grid-row: 2; }
        .down { grid-column: 2; grid-row: 3; }
        
        .game-info {
            background: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            text-align: center;
            font-size: 14px;
            color: #666;
            max-width: 300px;
        }
        
        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            display: none;
            z-index: 10;
        }
        
        .restart-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 25px;
            font-size: 16px;
            margin-top: 15px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .restart-btn:active {
            background: #5a6fd8;
        }
        
        @media (max-width: 480px) {
            #gameCanvas {
                width: 300px;
                height: 300px;
            }
            
            .controls {
                width: 180px;
                height: 180px;
            }
            
            .control-btn {
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="score-board">
        <div class="score">得分: <span id="score">0</span></div>
    </div>
    
    <div class="game-container">
        <canvas id="gameCanvas" width="320" height="320"></canvas>
        <div class="game-over" id="gameOver">
            <h2>游戏结束!</h2>
            <p>最终得分: <span id="finalScore">0</span></p>
            <button class="restart-btn" onclick="restartGame()">重新开始</button>
        </div>
    </div>
    
    <div class="controls">
        <div class="control-btn up" ontouchstart="changeDirection('UP')" onclick="changeDirection('UP')">↑</div>
        <div class="control-btn left" ontouchstart="changeDirection('LEFT')" onclick="changeDirection('LEFT')">←</div>
        <div class="control-btn right" ontouchstart="changeDirection('RIGHT')" onclick="changeDirection('RIGHT')">→</div>
        <div class="control-btn down" ontouchstart="changeDirection('DOWN')" onclick="changeDirection('DOWN')">↓</div>
    </div>
    
    <div class="game-info">
        <p>使用方向按钮控制蛇的移动</p>
        <p>吃食物增加长度和分数</p>
    </div>

    <script>
        // 游戏变量
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const finalScoreElement = document.getElementById('finalScore');
        const gameOverElement = document.getElementById('gameOver');
        
        // 游戏设置
        const gridSize = 16;
        const tileCount = canvas.width / gridSize;
        
        // 游戏状态
        let snake = [];
        let food = {};
        let direction = 'RIGHT';
        let nextDirection = 'RIGHT';
        let score = 0;
        let gameSpeed = 150;
        let gameInterval;
        let gameRunning = false;
        
        // 初始化游戏
        function initGame() {
            // 初始化蛇
            snake = [
                {x: 10, y: 10},
                {x: 9, y: 10},
                {x: 8, y: 10}
            ];
            
            // 生成食物
            generateFood();
            
            // 重置游戏状态
            direction = 'RIGHT';
            nextDirection = 'RIGHT';
            score = 0;
            scoreElement.textContent = score;
            gameOverElement.style.display = 'none';
            gameRunning = true;
            
            // 开始游戏循环
            if (gameInterval) clearInterval(gameInterval);
            gameInterval = setInterval(gameLoop, gameSpeed);
        }
        
        // 生成食物
        function generateFood() {
            food = {
                x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount)
            };
            
            // 确保食物不在蛇身上
            for (let segment of snake) {
                if (segment.x === food.x && segment.y === food.y) {
                    return generateFood();
                }
            }
        }
        
        // 游戏主循环
        function gameLoop() {
            if (!gameRunning) return;
            
            // 更新方向
            direction = nextDirection;
            
            // 移动蛇
            moveSnake();
            
            // 检查碰撞
            if (checkCollision()) {
                gameOver();
                return;
            }
            
            // 检查是否吃到食物
            checkFood();
            
            // 绘制游戏
            drawGame();
        }
        
        // 移动蛇
        function moveSnake() {
            // 创建新头部
            const head = {x: snake[0].x, y: snake[0].y};
            
            switch (direction) {
                case 'UP':
                    head.y -= 1;
                    break;
                case 'DOWN':
                    head.y += 1;
                    break;
                case 'LEFT':
                    head.x -= 1;
                    break;
                case 'RIGHT':
                    head.x += 1;
                    break;
            }
            
            // 将新头部添加到蛇的开头
            snake.unshift(head);
            
            // 移除尾部（除非吃到食物）
            snake.pop();
        }
        
        // 检查碰撞
        function checkCollision() {
            const head = snake[0];
            
            // 检查边界碰撞
            if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
                return true;
            }
            
            // 检查自身碰撞
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    return true;
                }
            }
            
            return false;
        }
        
        // 检查是否吃到食物
        function checkFood() {
            const head = snake[0];
            
            if (head.x === food.x && head.y === food.y) {
                // 增加蛇的长度
                snake.push({...snake[snake.length - 1]});
                
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                
                // 生成新食物
                generateFood();
                
                // 提高速度（可选）
                if (score % 50 === 0 && gameSpeed > 80) {
                    gameSpeed -= 5;
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, gameSpeed);
                }
            }
        }
        
        // 绘制游戏
        function drawGame() {
            // 清空画布
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格
            ctx.strokeStyle = '#e0e0e0';
            ctx.lineWidth = 0.5;
            for (let i = 0; i <= tileCount; i++) {
                ctx.beginPath();
                ctx.moveTo(i * gridSize, 0);
                ctx.lineTo(i * gridSize, canvas.height);
                ctx.stroke();
                
                ctx.beginPath();
                ctx.moveTo(0, i * gridSize);
                ctx.lineTo(canvas.width, i * gridSize);
                ctx.stroke();
            }
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#4CAF50';
                } else {
                    // 蛇身
                    ctx.fillStyle = '#8BC34A';
                }
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 1, gridSize - 1);
                
                // 蛇头的眼睛
                if (index === 0) {
                    ctx.fillStyle = '#000';
                    const eyeSize = gridSize / 5;
                    let eyeOffsetX = 0;
                    let eyeOffsetY = 0;
                    
                    switch (direction) {
                        case 'RIGHT':
                            eyeOffsetX = gridSize / 3;
                            eyeOffsetY = gridSize / 4;
                            break;
                        case 'LEFT':
                            eyeOffsetX = gridSize / 4;
                            eyeOffsetY = gridSize / 4;
                            break;
                        case 'UP':
                            eyeOffsetX = gridSize / 4;
                            eyeOffsetY = gridSize / 3;
                            break;
                        case 'DOWN':
                            eyeOffsetX = gridSize / 4;
                            eyeOffsetY = gridSize / 2;
                            break;
                    }
                    
                    ctx.fillRect(
                        segment.x * gridSize + eyeOffsetX,
                        segment.y * gridSize + eyeOffsetY,
                        eyeSize,
                        eyeSize
                    );
                }
            });
            
            // 绘制食物
            ctx.fillStyle = '#FF5722';
            ctx.beginPath();
            ctx.arc(
                food.x * gridSize + gridSize / 2,
                food.y * gridSize + gridSize / 2,
                gridSize / 2 - 1,
                0,
                2 * Math.PI
            );
            ctx.fill();
        }
        
        // 改变方向
        function changeDirection(newDirection) {
            // 防止反向移动
            if (
                (direction === 'UP' && newDirection === 'DOWN') ||
                (direction === 'DOWN' && newDirection === 'UP') ||
                (direction === 'LEFT' && newDirection === 'RIGHT') ||
                (direction === 'RIGHT' && newDirection === 'LEFT')
            ) {
                return;
            }
            
            nextDirection = newDirection;
        }
        
        // 游戏结束
        function gameOver() {
            gameRunning = false;
            clearInterval(gameInterval);
            finalScoreElement.textContent = score;
            gameOverElement.style.display = 'block';
        }
        
        // 重新开始游戏
        function restartGame() {
            initGame();
        }
        
        // 键盘控制（PC端）
        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp':
                    changeDirection('UP');
                    break;
                case 'ArrowDown':
                    changeDirection('DOWN');
                    break;
                case 'ArrowLeft':
                    changeDirection('LEFT');
                    break;
                case 'ArrowRight':
                    changeDirection('RIGHT');
                    break;
            }
        });
        
        // 防止页面滚动
        document.addEventListener('touchmove', (e) => {
            if (e.target.closest('.controls')) {
                e.preventDefault();
            }
        }, { passive: false });
        
        // 初始化游戏
        window.onload = function() {
            initGame();
        };
    </script>
</body>
</html>